<template>
  <div class="image-upload">
    <div class="upload">
      <input type="file" ref="file" @change="upload"/>
    </div>

    <img :src="content"/>
  </div>
</template>

<script lang="ts" setup>
 import { Ref, ref } from "@vue/reactivity"
 import { inject } from "@vue/runtime-core"

 const props = defineProps({
   defaultSrc: String
 })

 const emit = defineEmits(['submit'])
 const file = ref<HTMLInputElement>()
 const content = ref<string | File>(props.defaultSrc!)
 
 function upload(e: Event) {
   content.value = e.target!.files![0]
   let reader = new FileReader();
   reader.readAsDataURL(content.value);
   reader.addEventListener('load', function() {
     let result = this.result as string
     content.value = result
   })

   emit('submit', e.target!.files![0])
 }
</script>

<style lang="scss" scoped>
 div.upload {
   width: 80px;
   height: 20px;
   background: rgba(135, 206, 235, 0.2);
   border: 1px dashed black;
   border-radius: 5px;
   position: relative;

   &:hover {
     background: rgba(135, 206, 235, 1);
   }

   &:before {
     position: absolute;
     top: 0;
     left: 0;
     right: 0;
     bottom: 0;
     content: '上传图片';
     font-size: 13px;
     text-align: center;
     line-height: 20px;
     user-select: none;
   }

   input[type=file] {
     width: 100%;
     height: 100%;
     opacity: 0;
   }
 }

 img {
   width: 200px;
   height: 200px;
   object-fit: cover;
 }

</style>